import type { useFetch, UseFetchOptions } from "#app";
// import { useToken } from "~/store/token";
import { useRouter } from "vue-router";
import { useToken, useUserinfo, useRecord100 } from '~/store';

export const useServerRequest = <T = unknown>(
  url: string,
  opts: UseFetchOptions<T, unknown>
) => {
  const { token, setToken, delToken } = useToken()
  const { delUserinfo } = useUserinfo()
  const { setRecord100 } = useRecord100()
  const router = process.client ? null : useRouter();
  // const token = useToken().token;
  const runtimeConfig = useRuntimeConfig();

  const defaultOptions: UseFetchOptions<unknown> = {
    baseURL: runtimeConfig.public.baseUrl,
    onRequest({ options }) {
      options.headers = (options.headers || {}) as { [key: string]: string };
      if (!options.headers["Content-Type"]) {
        options.headers["Content-Type"] =
          options.method == "get" || options.method == "GET"
            ? "application/x-www-form-urlencoded"
            : "application/json";
      }
      options.headers["User-Token"] = token as string;
      options.method || "GET";
    },
    onResponse({ response }) {
      if (response.status === 200) {
        // 0:调用成功；100:未登录或Token失效；110:已在其它端登录；120:未绑定手机号；130:未设置密码；200:没有权限；300:传入参数有误；400:内部程序错误
        if (response._data.errno == 100) {
          // useToken().token = '';
          delToken()
          delUserinfo()
          setRecord100(true)
          if (process.client) {
            window.location.href = '/login';
            ElMessage.error(response._data.errmsg)
          }
          // else {
          //   router?.replace('/login')
          // }
        }
        else if (response._data.errno == 110) {
          // useToken().token = '';
          delToken()
          delUserinfo()
          if (process.client) {
            window.location.href = '/login';
            ElMessage.error(response._data.errmsg)
          }
          // else {
          //   router?.replace('/login')
          // }
        }
        else if (response._data.errno == 130) {
          // useToken().token = response._data.result.token;
          setToken(response._data.result.token)
          if (process.client) {
            window.location.href = '/setPassword';
            ElMessage.error(response._data.errmsg);
          } else {
            router?.replace('/setPassword')
          }
        }
        else if (response._data.errno == 200) {
          if (process.client) {
            window.location.href = '/';
            ElMessage.error(response._data.errmsg);
          } else {
            router?.replace('/')
          }
        }
        else if (response._data.errno == 300) {
          ElMessage({
            message: response._data.errmsg,
            type: 'error',
            appendTo: document.querySelector('.el-dialog') || document.body
          })
        }
        else if (response._data.errno == 400) {
          ElMessage({
            message: response._data.errmsg,
            type: 'error',
            appendTo: document.querySelector('.el-dialog') || document.body
          })
        }
      }
    },
    // onResponse({ response }) {
    //   if (+response.status === 200 && +response._data.code !== 200) {
    //     process.client && ElMessage.error(response._data.msg)
    //   }
    // },
    // onResponseError({ response }) {
    //   process.client && ElMessage.error(isArray(response._data.msg) ? response._data.msg[0] : response._data.msg)
    // },
  };

  return $fetch<T>(url, { ...defaultOptions, ...opts } as any);
};
